package com.fdb.efp.console.api.rest;

import com.fdb.basic.framework.core.constant.ApplicationConstance;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.basic.framework.web.controller.AbstractController;
import com.fdb.efp.console.api.service.AsyncExportTask;
import com.fdb.efp.console.service.facade.CusIndivService;
import com.fdb.efp.console.service.vo.CusHandoverAppVO;
import com.fdb.efp.console.service.vo.CusIndivVO;
import com.fdb.efp.console.service.facade.SRoleDataRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api")
public class CusIndivController extends AbstractController  {

	@Autowired
	@Qualifier("cusIndivService")
	private CusIndivService cusIndivService;

	@Autowired
	@Qualifier("sRoleDataRuleService")
	private SRoleDataRuleService sRoleDataRuleService;

	@Value("${CUSFILEPATH}")
	private String cusfilepath;

	@Autowired
	private AsyncExportTask asyncExportTask;

	/**relSerno
	 * 列表数据查询
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value="/cus/indivs", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<CusIndivVO>> queryCusIndivAll(@RequestBody CusIndivVO vo) {
		List<CusIndivVO> outputVo = new ArrayList<>();
		if (!StringUtil.isNullorBank(vo.getExportFlag()) && "exp".equals(vo.getExportFlag())) {
			outputVo = cusIndivService.queryExAllOwner(vo);
//			String fileName = "客户信息" + System.currentTimeMillis() + ".xlsx";
//			String filePath = cusfilepath + fileName;
//			//获取总条数
//			int count = cusIndivService.countCusIfosByCon(vo);
//			asyncExportTask.exportTask(vo,fileName,filePath,count);
//			return ResponseData.create(null,ApplicationConstance.SUCCESS,"！",true);
		} else if (StringUtil.isNullorBank(vo.getExportFlag())){
			outputVo = cusIndivService.queryAllOwner(vo);
		}

		return getResponseData(outputVo);
	}

//	@RequestMapping(value="/cus/indivs/export", method=RequestMethod.POST)
//	public @ResponseBody ResponseData<List<CusIndivVO>> queryCusIndivInfos(@RequestBody CusIndivVO vo) {
//		String fileName = "客户信息" + System.currentTimeMillis() + ".xlsx";
//		String filePath = cusfilepath + fileName;
//		asyncExportTask.exportTask(vo,fileName,filePath);

//		Callable<String> callable = () -> {
//			try {
//				//获取总条数
//				int count = cusIndivService.countCusIfosByCon(vo);
//				//计算查询次数
//				int loopTimes = count / pagesize;
//				int remainCount = count % pagesize;
//				if (remainCount != 0) loopTimes += 1;
//				//设置分页信息
//				vo.setSize(pagesize);
//				vo.setTotal(count);
//				//导出数据
//				ExcelWriter writer = EasyExcel.write(filePath,WriteCusIndivModel.class).build();
//				for (int i = 0; i < loopTimes; i++) {
//					vo.setPage(i + 1);
//					List<CusIndivVO> writeCusIndivList = cusIndivService.queryExAllOwner(vo);
//					List<WriteCusIndivModel> writeModelList = copyBeansVal(writeCusIndivList);
//					if (Objects.nonNull(writeModelList) && !writeModelList.isEmpty()) {
//						//导出数据
//						WriteSheet writeSheet = EasyExcel.writerSheet(i,fileName + i).build();
//						writer.write(writeModelList, writeSheet);
//					}
//				}
//				writer.finish();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			return "导出结束！";
//		};
//		WebAsyncTask<String> webAsyncTask = new WebAsyncTask<>(300000,callable);
//		webAsyncTask.onTimeout(()->{return "执行超时！";});
//		webAsyncTask.onError(()->"处理异常！");
//		return ResponseData.create(null,ApplicationConstance.SUCCESS,"接收到处理请求！",true);
//	}

	/*private WebAsyncTask<String> exportCusDatas(CusIndivVO vo, String fileName, String filePath) {

		Callable<String> callable = () -> {
			try {
				//获取总条数
				int count = cusIndivService.countCusIfosByCon(vo);
				//计算查询次数
				int loopTimes = count / pagesize;
				int remainCount = count % pagesize;
				if (remainCount != 0) loopTimes += 1;
				//设置分页信息
				vo.setSize(pagesize);
				vo.setTotal(count);
				//导出数据
				ExcelWriter writer = EasyExcel.write(filePath,WriteCusIndivModel.class).build();
				for (int i = 0; i < loopTimes; i++) {
					vo.setPage(i + 1);
					List<CusIndivVO> writeCusIndivList = cusIndivService.queryExAllOwner(vo);
					List<WriteCusIndivModel> writeModelList = copyBeansVal(writeCusIndivList);
					if (Objects.nonNull(writeModelList) && !writeModelList.isEmpty()) {
						//导出数据
						WriteSheet writeSheet = EasyExcel.writerSheet(i,fileName + i).build();
						writer.write(writeModelList, writeSheet);
					}
				}
				writer.finish();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "导出结束！";
		};
		WebAsyncTask<String> webAsyncTask = new WebAsyncTask<>(callable);
		webAsyncTask.onError(()->"处理异常！");
		return webAsyncTask;
	}*/

	/*private List<WriteCusIndivModel> copyBeansVal(List<CusIndivVO> writeCusIndivList) {
		List<WriteCusIndivModel> writeModelList = new ArrayList<>();
		writeCusIndivList.forEach(item->{
			WriteCusIndivModel writeCusIndivModel = new WriteCusIndivModel();
			writeCusIndivModel.setCertCode(item.getCertCode());
			writeCusIndivModel.setCertType(item.getCertType());
			writeCusIndivModel.setCreateTime(TimeUtil.getCurrentDateTime());
			writeCusIndivModel.setCusId(item.getCusId());
			writeCusIndivModel.setCusName(item.getCusName());
			writeCusIndivModel.setFstAppChannel(item.getFstAppChannel());
			writeCusIndivModel.setIndivSex(Sex.MALE.getEnname().equals(item.getIndivSex())?Sex.MALE.getCnname():Sex.FEMALE.getCnname());
			writeCusIndivModel.setPhone(item.getPhone());
			writeModelList.add(writeCusIndivModel);
		});
		return writeModelList;
	}*/

	/**
	 * 用客户号或者证件号查询客户信息
	 * @return
	 */
	@RequestMapping(value="/cus/indiv/{condition}", method=RequestMethod.GET)
	public @ResponseBody ResponseData<CusIndivVO> queryByPk(@PathVariable("condition") String condition) {
		//客户号查询
		CusIndivVO inVo = new CusIndivVO();
		inVo.setCusId(condition);
		CusIndivVO outputVoByPk = cusIndivService.queryByPk(inVo);
		//证件号查询
		CusIndivVO inVo1 = new CusIndivVO();
		inVo1.setCertCode(condition);
		CusIndivVO outputVoByCon = cusIndivService.queryByCondition(inVo1);
		if (Objects.nonNull(outputVoByPk)){
			return ResponseData.create(outputVoByPk,ApplicationConstance.SUCCESS,"通过客户号查询客户表成功！",true);
		}
		else if (Objects.nonNull(outputVoByCon)) {
			return ResponseData.create(outputVoByCon,ApplicationConstance.SUCCESS,"通过证件号查询客户表成功！",true);
		}
		return ResponseData.create(null,ApplicationConstance.FAILURE,"查询客户表结果为空！",false);
	}

	/**
	 * 根据主键删除信息
	 * @param cusIndiv
	 * @return
	 */
	@RequestMapping(value="/cus/indiv", method=RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody CusIndivVO inCusIndivVo) {
		int outputVo = cusIndivService.deleteByPk(inCusIndivVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键更新信息
	 * @param inCusIndivVo
	 * @return
	 */
	@RequestMapping(value="/cus/indiv", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody CusIndivVO inCusIndivVo) {
//		Map<String,String> key = new HashMap<>();
//		key.put("cusId", inCusIndivVo.getCusId());
//		boolean checkRlt = this.checkOptionalAuthority(key, "/api/cus/indivs",this.cusIndivService);
//		if(checkRlt) {
//			inCusIndivVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
//			int outputVo = cusIndivService.updateByPk(inCusIndivVo);
//			return getResponseData(outputVo);
//		}else {
//			return ResponseData.create(null, ApplicationConstance.NO_AUTHORITY, ApplicationConstance.NO_AUTHORITY_MESSAGE, false);
//		}
		int outputVo = 0;
		setUserInfoToVO(inCusIndivVo);
		// 根据婚姻状况清空婚姻信息
		if ("10".equals(inCusIndivVo.getIndivMarSt()) ||
				"30".equals(inCusIndivVo.getIndivMarSt()) ||
				"40".equals(inCusIndivVo.getIndivMarSt()) ||
				"90".equals(inCusIndivVo.getIndivMarSt())){
			inCusIndivVo.setIndivSpsName("");
			inCusIndivVo.setIndivSpsMphn("");
			inCusIndivVo.setIndivSpsPhone("");
		}
		inCusIndivVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
		inCusIndivVo.setLastUpdateUser(inCusIndivVo.getLoginUserId());
		outputVo = cusIndivService.updateByPk(inCusIndivVo);
		return getResponseData(outputVo);
	}

	/**
	 * 新增数据
	 * @param inCusIndivVo
	 * @return
	 */
	@RequestMapping(value="/cus/indiv", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertCusIndiv(@RequestBody CusIndivVO inCusIndivVo) {
		int outputVo = cusIndivService.insertCusIndiv(inCusIndivVo);
		return getResponseData(outputVo);

	}

	/**
	 * 新增数据
	 * @param inCusIndivVo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/cus/cusrisk/test3", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Boolean> test3() throws Exception {
		logger.info("开始调用上传ODS的方法");
//		Boolean outputVo = batUploadCusIndivService.custListToODS();
		return getResponseData(false);

	}
	/**
	 * 移交明细下的客户信息查询
	 * @param vo
	 * @return
	 */
	@RequestMapping(value="/cus/indivs/handover", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<CusIndivVO>> queryCusIndivByCusManager(
			@RequestBody CusIndivVO vo) {
		setUserInfoToVO(vo);
		vo.setCusManager(vo.getLoginUserId()); //当前登录人为客户经理
		List<CusIndivVO> outputVo = cusIndivService.queryCusIndivByCusManager(vo);
		return getResponseData(outputVo);
	}
	/**
	 * 根据区域编码,客户经理号 查询所有的客户信息
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/cus/indivs/handover/areacode", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<CusIndivVO>> queryCusByCusManagerArea(
			@RequestBody CusIndivVO vo) {
		List<CusIndivVO> outputVo = cusIndivService.queryCusByCusManagerArea(vo);
		return getResponseData(outputVo);
	}
	/**
	 * 查找客户经理下移交日期在一年内接收到 所有客户信息
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/cus/indivs/handover/history", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<CusIndivVO>> queryCusByHandoverHis(
			@RequestBody CusIndivVO vo) {
		List<CusIndivVO> outputVo = cusIndivService.queryCusByHandoverHis(vo.getCusManager());
		return getResponseData(outputVo);
	}
	/**
	 * 查询客户经理下未开始移交的所有客户
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/cus/indivs/cus/manager", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<CusIndivVO>> queryCusByCusManager(
			@RequestBody CusIndivVO vo) {
		setUserInfoToVO(vo);
		vo.setCusManager(vo.getLoginUserId());
		// 有[移交范围]为按客户经理的移交未结束，请撤销或者完成后再进行申请
		CusHandoverAppVO inCusHandoverAppVo = new CusHandoverAppVO();
		inCusHandoverAppVo.setHandoverId(vo.getLoginUserId());
//		int num = cusHandoverAppService.queryHandoverCusManager(inCusHandoverAppVo);
		int num = 0;
		if ( num > 0 ) {
			ResponseData<List<CusIndivVO>> responseData = new ResponseData<List<CusIndivVO>>();
			responseData.setRows(null);
			responseData.setMessage("有[移交范围]为按客户经理的移交未结束，请撤销或者完成后再进行申请!");
			responseData.setCode(ApplicationConstance.FAILURE);
			responseData.setSuccess(false);
			return responseData;
		}

		List<CusIndivVO> outputVo = cusIndivService.queryCusAllByCusManager(vo);
		return getResponseData(outputVo);
	}

	/**
	 * 导出查询到的所有客户信息
	 * @param vo
	 * @return
	 * @author qiuyf
	 * @since 2018年12月28日 下午4:45:06
	 * @version 1.0
	 */
	@RequestMapping(value = "/cusRelCheck/records/export", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<CusIndivVO>> exportCusRelCheckInfos(@RequestBody CusIndivVO vo) {
		ResponseData<List<CusIndivVO>> outputVo = this.queryCusIndivAll(vo);
		return outputVo;
	}


}
